package com.exam.servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.exam.domain.entity.*;

import com.exam.service.ExamService;
import com.exam.service.RecordService;
import com.exam.service.StudentService;
import com.exam.service.impl.ExamServiceImpl;
import com.exam.service.impl.RecordServiceImpl;
import com.exam.service.impl.StudentServiceImpl;
import com.exam.util.BaseResult;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/student/*",asyncSupported = true)
public class StudentServlet extends HttpServlet {

    private StudentService studentService;
    private ExamService examService;
    private RecordService recordService;

    @Override
    public void init() throws ServletException {
        super.init();
        studentService = new StudentServiceImpl();
        examService = new ExamServiceImpl();
        recordService = new RecordServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI(); // 获取请求的URI
        System.out.println(path);
        if (path.endsWith("/home")) {
            // 页面逻辑处理，返回 home.jsp 视图
            System.out.println("转发到学生端首页");
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/student/home.jsp");
            dispatcher.forward(req, resp);  // 转发到 home.jsp
//            resp.sendRedirect("/WEB-INF/pages/home.jsp");
        } else if (path.endsWith("/examList")) {
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/student/examList.jsp");
            dispatcher.forward(req, resp);
        } else if (path.endsWith("/logout")){
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/student/logout.jsp");
            dispatcher.forward(req, resp);
        }else if (path.endsWith("/viewExamRecords")){
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/student/viewExamRecords.jsp");
            dispatcher.forward(req, resp);
        }else if (path.endsWith("/info")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer studentId = user.getUserId();
            BaseResult<Student> result = studentService.getStudentInfoByStudentId(studentId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if (path.endsWith("/exams")){
            // 其他处理逻辑
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer studentId = user.getUserId();
            // 同时获取学生是否已经参加过这个试卷，不可以重复提交
            BaseResult<List<Exam>> result = studentService.getExamList(studentId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/examDetails")){
            //开启异步请求
            req.startAsync();
            // 获取？id=xxx的参数，试卷id
            Integer examId = Integer.parseInt(req.getParameter("id"));
            // 查询试卷详情信息
            BaseResult<Exam> result =  examService.findExamItemsByExamId(examId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getExamRecords")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer studentId = user.getUserId();
            // 获得学生的考试记录，列表
            BaseResult<List<Record>> result = recordService.getExamRecords(studentId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);

            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getExamSolution")){
            // 查询试题解析
            req.startAsync();
            // 获取考试记录ID
            Integer recordId = Integer.parseInt(req.getParameter("recordId"));

            // 获得学生的考试记录，列表
            BaseResult<Record> result = recordService.getExamRecordItemsById(recordId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            req.getAsyncContext().complete();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入post方法");
        String path = req.getRequestURI(); // 获取请求的URI
        if (path.contains("/submitExam")) {
            //开启异步请求
//            req.startAsync();
            // 获取？id=xxx的参数，试卷id
//            Integer examId = Integer.parseInt(req.getParameter("id"));
            // 读取请求体
            req.setCharacterEncoding("UTF-8"); // 设置请求编码
            User user = (User)req.getSession().getAttribute("user");
            // 学生ID
            Integer studentId = user.getUserId();
            // 获取请求体
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String jsonString = sb.toString();

            // 使用 fastjson 解析 JSON 字符串
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONArray answersArray = jsonObject.getJSONArray("answers");  // 获取 "answers" 数组
            Integer examId = jsonObject.getInteger("id");  // 获取 "answers" 数组

            // 将 answers 转换成 List
            List<Answer> answers = JSONArray.parseArray(answersArray.toJSONString(), Answer.class);

            BaseResult<String> result = studentService.submitExam(studentId,examId,answers);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
//            req.getAsyncContext().complete();
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);
    }
}
